﻿using AssetsSys.BLL;
using AssetsSys.WebApi.Filters;
using AssetsSys.WebApi.Models.Users;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using System.Web.Http.Cors;
using AssetsSys.Dto;
using AssetsSys.Dto.Permission;
using AssetsSys.Dto.User;
using AssetsSys.WebApi.Models.Auth;

namespace AssetsSys.WebApi.Controllers
{
    //过滤器
    /// <summary>
    /// 用户管理
    /// </summary>
    [MyAuth]
    //允许跨域
    [EnableCors(origins: "*", headers: "*", methods: "*")]
    [RoutePrefix("api/users")]
    public class UserController : ApiController
    {
        //跳过过滤器
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        [Route("token")]
        public IHttpActionResult Login([FromBody]LoginViewModel model)
        {
            if (ModelState.IsValid)
            {
                //viewmodel校验合法性
                if (UserManger.Login(model.Phone, model.Password, out Guid userid, out string userName, out bool isForbid))
                {
                    if (isForbid)
                    {
                        return this.ErrorData("账号被禁用,请联系管理员");
                    }
                    return this.SendData(JwtTools.Encoder(new Dictionary<string, object> {
                        { "username",userName},
                        { "userid",userid}
                    }));
                }
                else
                {
                    return this.ErrorData("账号或密码错误");
                }
            }
            else
            {
                return this.ErrorData("您输入的数据不合法");
            }
        }

        /// <summary>
        /// 添加用户
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("account")]
        public async Task<IHttpActionResult> CreateUser(CreateUserViewModel model)
        {
            if (!ModelState.IsValid) return this.ErrorData(ModelState.Values.FirstOrDefault()?.Errors[0].ErrorMessage);
            var success = await UserManger.CreateUser(model.UserName, model.PassWord,
                    model.Email, model.Phone, model.DepartmentId);
                return success ? this.SendData("添加成功") : this.ErrorData("手机号重复");
           
        }

        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="userid">用户Id</param>
        /// <returns></returns>
        [HttpGet]
        [Route("{userid}/account")]
        public async Task<IHttpActionResult> GetDepartment(Guid userid)
        {
            var model = await UserManger.GetById(userid);
            model.PassWord = "";
            return this.SendData(model);
        }

        /// <summary>
        /// 更新用户信息
        /// </summary>
        /// <param name="userid">用户Id</param>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPut]
        [Route("{userid}/account")]
        public async Task<IHttpActionResult> UpdateDepartment(Guid userid, UserModel model)
        {
            model.Id = userid;
            return await UserManger.Update(model) ? this.SendData("修改成功") : this.ErrorData("修改失败");
        }

        /// <summary>
        /// 获取用户目录
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("permission")]
        public async Task<IHttpActionResult> GetPermissionList()
        {
            var userid = ((UserIdentity)User.Identity).Id;
            var permission = await UserManger.GetPermissionByUserId(userid);
            return this.SendData(permission);
        }

        /// <summary>
        /// 获取用户列表
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("list")]
        public async Task<IHttpActionResult> GetUserList([FromUri] UserRequestDto request)
        {
            var userid = ((UserIdentity)User.Identity).Id;
            var userListData = await UserManger.GetUserList(request, userid);
            return this.SendData(userListData);
        }

        /// <summary>
        /// 用户禁用
        /// </summary>
        /// <param name="userid">禁用或启用的Id</param>
        /// <returns></returns>
        [HttpPost]
        [Route("{userid}/ban_user")]
        public async Task<IHttpActionResult> BanUser(Guid userid)
        {
            var success = await UserManger.BanUser(userid);
            return success ? this.SendData("变动成功") : this.ErrorData("变动失败");
        }

        /// <summary>
        /// 修改用户密码
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPut]
        [Route("reset_password")]
        public async Task<IHttpActionResult> ResetPassWord(EditPassWordViewModel model)
        {
            var userid = ((UserIdentity)User.Identity).Id;
            var oldModel = await UserManger.GetById(userid);
            if (oldModel.PassWord!= model.OldPassWord)
            {
                return this.ErrorData("原密码不正确");
            }
            if (oldModel.PassWord == model.NewPassWord)
            {
                return this.ErrorData("新旧密码相同哟");
            }
            oldModel.PassWord = model.NewPassWord;
            return await UserManger.Update(oldModel) ? this.SendData("修改成功") : this.ErrorData("修改失败");
        }
    }
}
